package com.itita.ww2.redis;

import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RedisUtil {
	public static final String keySplit = ":";
	public static final String KEY_INDEX = "index";

	/**
	 * 组合key
	 */
	public static final String combineKey(Object... keys) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < keys.length; ++i) {
			if (keys[i] instanceof String[]) {
				String[] keysList = (String[]) keys[i];
				for (int j = 0; j < keysList.length; ++j) {
					sb.append(keysList[j]);
					if (j != keysList.length - 1) {
						sb.append(keySplit);
					}
				}
			} else {
				sb.append(keys[i]);
				if (i != keys.length - 1) {
					sb.append(keySplit);
				}
			}
		}
		return sb.toString();
	}

	/**
	 * 分离key
	 */
	public static final String splitKeyAsString(String key, int splitCount, boolean reverse) {
		List<String> result = new ArrayList<>();
		Collections.addAll(result, key.split(keySplit));
		for (int i = 0; i < splitCount; ++i) {
			if (reverse) {
				result.remove(result.size() - 1);
			} else {
				result.remove(0);
			}
		}
		return combineKey(result.toArray());
	}

	/**
	 * 分离key
	 */
	public static final String[] splitKeyAsArray(String key, int splitCount, boolean reverse) {
		List<String> result = new ArrayList<>();
		Collections.addAll(result, key.split(keySplit));
		for (int i = 0; i < splitCount; ++i) {
			if (reverse) {
				result.remove(result.size() - 1);
			} else {
				result.remove(0);
			}
		}
		return result.toArray(new String[] {});
	}

	public static boolean isDouble(String val) {
		try {
			Double.parseDouble(val);
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

	public static String getJarPath() {
		URL url = RedisUtil.class.getProtectionDomain().getCodeSource().getLocation();
		String filePath = null;
		try {
			filePath = URLDecoder.decode(url.getPath(), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (filePath.endsWith(".jar")) {
			filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
		}
		return filePath;
	}

	/**
	 * 生成key
	 */
	public static String[] genericKey(Object... keys) {
		List<String> arr = new ArrayList<>();
		for (int i = 0; i < keys.length; ++i) {
			arr.add(String.valueOf(keys[i]));
		}
		return arr.toArray(new String[] {});
	}
}
